package cn.kkcxy.blog.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * @BelongsProject: kkcxy-blog
 * @BelongsPackage: cn.kkcxy.blog.common.config
 * @Author: kkcxy
 * @CreateTime: 2024-09-18 00:05
 * @Description: 线程池配置
 * @Version: 1.0
 */
@Slf4j
@Configuration
public class TaskExecutePool {

    /**
     * @description: Async Server Executor
     **/
    @Bean
    public Executor asyncServerExecutor() {
        log.info("register async server executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(4);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("async-server-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * @description: Archive ThreadPool
     **/
    @Bean(name = "archiveThreadPool")
    public ThreadPoolExecutor getArchiveThreadPool() {
        return new ThreadPoolExecutor(
                4, // 核心数
                8, // 最大线程数
                3, // 保持活跃时间
                TimeUnit.SECONDS, // 单位
                new LinkedBlockingDeque<>(40), // 队列
                Executors.defaultThreadFactory(), // 线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
    }

    /**
     * @description: Common ThreadPool
     **/
    @Bean(name = "commonThreadPool")
    public ThreadPoolExecutor getArticleThreadPool() {
        return new ThreadPoolExecutor(
                2, // 核心数
                4, // 最大线程数
                3, // 保持活跃时间
                TimeUnit.SECONDS, // 单位
                new LinkedBlockingDeque<>(40), // 队列
                Executors.defaultThreadFactory(), // 线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy()); // 拒绝策略
    }
}
